<%@ page import="unilearn.facade.FileFacade" %>
<%@ page import="unilearn.domain.DataFile" %>
<%@ page import="javax.servlet.ServletOutputStream" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.IOException" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="org.apache.commons.fileupload.util.Streams" %> 

<%
if (request.getParameter("fileid") != null) {
	try {
		DataFile toSend = FileFacade.getFileByID(Long.parseLong(request.getParameter("fileid")));

		if (toSend != null) {
			response.setContentType(toSend.getFileType());
			response.setContentLength((int) toSend.getFileSize());
			response.setHeader("Content-Disposition", "attachment; filename=\"" + toSend.getFileName() + "\"");

			FileInputStream inStream = new FileInputStream(toSend.getFile());
			ServletOutputStream outStream = response.getOutputStream();

			Streams.copy(inStream, outStream, true);

			toSend.getFile().delete(); // delete file from disk after data has been streamed to client
		} else {
			response.sendError(response.SC_NOT_FOUND);
		}
	} catch (SQLException e) {
		out.println(e.getMessage());
	} catch (NamingException e) {
		out.println(e.getMessage());
	} catch (IOException e) {
		out.println(e.getMessage());
	}
	
	
} else {
	response.sendError(response.SC_NOT_FOUND);
}
%>
